<template>
  <q-page class="q-pa-md wrapBox" v-loading="loading">
    <div class="nav">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <el-image src="/svgs/titleIcon.svg" style="width: 17px;margin-top: 2px" fit />
        </el-breadcrumb-item>
        <el-breadcrumb-item>数据中心</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ name: 'dataset' }">数据集</el-breadcrumb-item>
        <el-breadcrumb-item><span style="color: #333;">新建数据集</span></el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="datasetBox" style="position: relative">
      <div class="title">新建数据集</div>
      <div class="contentBox">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm typeBox"
          style="max-width: 50%;" status-icon>
          <el-form-item label="数据集名称：" prop="title">
            <el-input v-model.trim="ruleForm.title" placeholder="请输入数据集名称" show-word-limit spellcheck="false" />
          </el-form-item>
          <el-form-item label="数据集说明：" prop="description">
            <el-input v-model.trim="ruleForm.description" type="textarea" spellcheck="false" placeholder="请输入" :rows="5"
              show-word-limit maxlength="100" />
          </el-form-item>
          <el-form-item label="数据类型：" prop="dataset_type" style="margin: 0">
            <el-radio-group v-model="tabPosition" @change="handleRadioChange">
              <el-radio-button label="Sequence">序列/结构文件</el-radio-button>
              <el-radio-button label="Image">图片</el-radio-button>
              <el-radio-button label="TimeSeries">时序数据</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item style="margin: 0" v-if="tabPosition === 'Sequence'">
            <p style="margin: 0; font-size: 13px">
              支持序列文件: fasta、支持蛋白结构文件: pdb
            </p>
          </el-form-item>
          <el-form-item style="margin-top: 10px" label="数据上传：" prop="file_ids" ref="imageOfFrom">
            <el-tabs :tab-position="tabPosition" style="display: flex;flex-direction: column" class="demo-tabs">
              <div v-for="item in datasetType" :key="item.type" class="row labelTypeBox" v-show="tabPosition == item.type"
                style="flex-direction: column">
                <box-loading v-if="boxLoadState"></box-loading>
                <el-upload class="upload-demo uploadBox" drag :show-file-list="false" :http-request="uploadFile"
                  :file-list="uploadFileList" :before-upload="checkFileType" multiple :on-change="handleFileChanged"
                  :on-remove="removeListData" style="width: 350px;height: 222px;background-color: #d9d9d9!important;">
                  <div class="el-upload__text uploadBoxBtn">
                    <el-image :src="imgUrl" fit />
                    <div style="color: #333333;font-size: 14px">点击选择文件或将文件拖拽到这里上传</div>
                    <div>支持上传文件格式：{{ item.format }}</div>
                  </div>
                </el-upload>
                <div style="width: 280px;" :class="{ 'listOverflowScroll': uploadFileList.length > 4 }">
                  <ul class="el-upload-list el-upload-list--text">
                    <li class="el-upload-list__item is-success" v-for="(item, index) in uploadFileList" :key="index"
                      style="display: flex;align-items: center;justify-content: space-between">
                      <a class="el-upload-list item-name"
                        style="width: 80%;overflow:hidden;white-space: nowrap;text-overflow: ellipsis;">
                        <i class="el-icon-document"> </i>
                        {{ item.row_name }}
                      </a>
                      <el-icon style="margin-top: 5px" @click="handleRemove(index)">
                        <Close />
                      </el-icon>
                    </li>
                  </ul>
                </div>
              </div>
            </el-tabs>
          </el-form-item>
          <el-form-item label="输入版本号：" prop="version">
            <el-input v-model.trim="ruleForm.version" spellcheck="false" placeholder="请输入版本号,例: v1、v001" />
          </el-form-item>
        </el-form>
      </div>
      <div class="row"
        style="display:flex;justify-content: flex-end;margin: 10px 0 0 0;padding: 10px 0;background-color: #fff">
        <el-button v-if="!store.quickStart.quickFlow" @click="resetForm(ruleFormRef)"
          style="background-color: #fff!important;">取消</el-button>
        <el-button v-if="!store.quickStart.quickFlow" type="primary" @click="submitForm(ruleFormRef)">
          完成
        </el-button>
        <el-button v-if="store.quickStart.quickFlow" type="primary" @click="submitForm(ruleFormRef)">
          下一步
        </el-button>

      </div>
    </div>
  </q-page>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, shallowRef } from 'vue';
import boxLoading from 'src/components/boxLoading.vue';
import { useRouter } from 'vue-router';
import type { FormInstance, FormRules } from 'element-plus';
import { getDatalabelListApi, uploadFileApi } from 'src/api/common';
import {
  createModelData,
  getDatasetType,
  validateDatasetListTitle,
} from 'src/api/dataset';
import { putQuickStartFlow } from 'src/api/project'
import { ElMessage } from 'element-plus';
import imgUrl from 'assets/dataSet/grayUpload.png';
import { dataSetStore } from 'src/stores/dataSet'
// import {validateModelName} from "src/api/model";
const store = dataSetStore()
const fileType = ref();
const uploadFileList: any = ref([]);
const router = useRouter()
const projectId = router.currentRoute.value.params.project_id
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive({
  title: '',
  description: '',
  dataset_type: '',
  file_ids: <any>[],
  version: '',
});
const labelSate = ref('false');
const loading = ref(true);
const imageOfFrom = ref();
let datasetType = ref([]);
// 图片
let imgOption: any = ref([]);
// 标注场景时序数据
let dataOption: any = ref([]);
// 标注场景文本
let textOption: any = ref([]);

const validateTitle = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error('数据集名称不能为空'));
    return;
  }
  if (value.length < 4) {
    callback(new Error('字段长度最小长度为4'));
    return;
  }
  if (value.length > 16) {
    callback(new Error('字段长度最大长度为16'));
    return;
  }
  let params = {
    title: ruleForm.title,
  };
  validateDatasetListTitle(projectId, params)
    .then((res: any) => {
      if (res.data.msg) {
        callback(new Error(res.data.msg));
      }
      callback();
    })
    .catch((err: any) => {
      callback(new Error('校验接口报错'));
    });
};

const rules = reactive<FormRules>({
  title: [{ required: true, validator: validateTitle, trigger: 'blur' }],
  dataset_type: [
    {
      required: true,
      message: '请选择数据类型',
      trigger: 'blur',
    },
  ],
  file_ids: [
    {
      required: true,
      message: '数据上传不能为空',
      trigger: ['blur', 'change'],
    },
  ],
  version: [
    { required: true, message: '输入版本号', trigger: ['blur', 'change'] },
  ],
});
const tabPosition = ref('Sequence');

onMounted(() => {
  getDatasetType().then((res: any) => {
    let imageIndex = res.data.findIndex((v: any) => {
      return v.type == 'Image';
    });
    let sequenceIndex = res.data.findIndex((v: any) => {
      return v.type == 'Sequence';
    });
    let timeSeriesIndex = res.data.findIndex((v: any) => {
      return v.type == 'TimeSeries';
    });
    datasetType.value = [
      res.data[sequenceIndex],
      res.data[imageIndex],
      res.data[timeSeriesIndex],
    ];
  });
});

//数据类型切换
function handleRadioChange(value: any) {
  uploadFileList.value = [];
  imageOfFrom.value.clearValidate();
  ruleForm.file_ids = [];
}

//点击上传
const paramObj = shallowRef();
const boxLoadState = ref(false);
const checkState = ref(false);
const emits = defineEmits(['formData']);
function uploadFile(obj: any) {
  imageOfFrom.value.clearValidate();
  paramObj.value = new FormData();
  paramObj.value.append('file', obj.file);
  paramObj.value.append('date', obj.file.name);
  checkState.value = true;
  boxLoadState.value = true;
  uploadFileApi(paramObj.value).then((res) => {
    uploadFileList.value.push(res.data);
    ruleForm.file_ids.push(res.data.id);
    checkState.value = false;
    boxLoadState.value = false;
  });
}
function handleRemove(index: number) {
  boxLoadState.value = true;
  uploadFileList.value.splice(index, 1);
  ruleForm.file_ids.splice(index, 1);
  boxLoadState.value = false;
}
// 删除上传文件列表的某个值
function removeListData(file: any, fileList: any) {
  let filterArrIndex = uploadFileList.value.findIndex((item: any) => {
    return item.file.indexOf(file.name) > -1;
  });
  uploadFileList.value.splice(filterArrIndex, 1);
  ruleForm.file_ids.splice(filterArrIndex, 1);
}
const handleFileChanged = (file: any, fileList: any) => {
  // 检查是否有重复文件
  if (
    uploadFileList.value.findIndex((f: any) => f.row_name == file.name) != -1
  ) {
    let index = uploadFileList.value.findIndex((f: any) => f.row_name == file.name)
    ElMessage.error(file.name + '该文件已存在');
    fileList.pop();
    uploadFileList.value.splice(index, 1);
    ruleForm.file_ids.splice(index, 1);
  }
};
function checkFileType(file: any, fileList: any) {
  let dataList = JSON.parse(JSON.stringify(datasetType.value));
  let filterDataList = dataList.filter(
    (item: any) => item.type === tabPosition.value
  );
  const fileName = file.name;
  const fileTypeName = fileName.substring(fileName.lastIndexOf('.') + 1);
  const isFileType = filterDataList[0].format.includes(fileTypeName);
  if (isFileType == false) {
    ElMessage.error(`上传类型错误，请选择${filterDataList[0].format}格式文件`);
    fileList.pop();
  }
  let isLt2k = file.size / 1024 / 1024 / 1024 < 2 ? '1' : '0';
  if (isLt2k == '0') {
    ElMessage.error(`上传文件过大，请选择小于2G的文件`);
    fileList.pop();
  }
}

// 对象数组去重
const filterArr = (arr: any) => {
  const uniqueArr = arr.reduce((unique: any, item: any) => {
    if (!unique.some((obj: any) => obj.value === item.value)) {
      unique.push(item);
    }
    return unique;
  }, []);
  return uniqueArr;
};

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  ruleForm.dataset_type = tabPosition.value;
  await formEl.validate((valid, fields) => {
    if (valid) {
      createModelData(projectId, ruleForm).then((res: any) => {
        if (store.quickStart.quickFlow) {
          putQuickStartFlow(projectId, { stage: 2 }).finally(() => {
            router.push({ name: 'quick-start', params: { project_id: projectId } })
          })
        } else {
          router.push({ name: 'dataset', params: { project_id: projectId } });
        }



      });
    } else {
      console.log('error submit!', fields);
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  router.push({ name: 'dataset', params: { project_id: projectId } });
};
initOption();
function initOption() {
  loading.value = true;
  getDatalabelListApi().then((res) => {
    imgOption.value = filterType(res.data, 'Image');
    dataOption.value = filterType(res.data, 'TimeSeries');
    textOption.value = filterType(res.data, 'Text');
    loading.value = false;
  });
}

function filterType(arr: any, str: string) {
  let newArr = arr.filter((item: any, index: number) => {
    if (item.data_type == str) return item;
  });
  return newArr;
}
</script>

<style scoped lang="scss">
.nav {
  display: flex;
  align-items: center;
  padding-left: 20px;
  cursor: pointer;
  background-color: #f6f8fa;
  height: 46px;

  ::v-deep .el-breadcrumb {
    display: flex;
    align-items: center;
  }
}

.wrapBox {
  padding: 0 !important;

  .datasetBox {
    margin: 0 20px;

    .title {
      width: 100%;
      padding: 12px;
      box-sizing: border-box;
      background-color: #fff;
      color: #333;
      font-weight: 500;
      text-align: left;
      line-height: 24px;
      border-bottom: 2px solid #f6f8fa;
    }

    .contentBox {
      padding: 12px;
      background-color: #ffffff !important;
    }
  }
}

//间距
.el-form-item {
  margin-bottom: 20px;
}

//面包屑斜杆
::v-deep .el-breadcrumb__separator {
  font-size: 12px !important;
  color: #c9cdd4 !important;
  margin-top: 2px !important;
}

//面包屑中的文字颜色
::v-deep .el-breadcrumb__inner {
  color: #666 !important;
}

::v-deep .el-breadcrumb__inner.is-link,
.el-breadcrumb__inner a {
  font-weight: normal !important;
}

::v-deep .el-radio-button__inner {
  width: 150px !important;
  background: #fafafa !important;
}

::v-deep .el-upload-dragger {
  background-color: #fafafa !important;
  border-radius: 0 !important;
}

::v-deep .upload-demo {
  height: 175px !important;
}

:deep(.el-input__inner::placeholder),
:deep(.el-textarea__inner::placeholder) {
  color: #cccccc;
  font-size: 14px;
  font-weight: 400;
}

::v-deep .el-radio-button__original-radio:checked+.el-radio-button__inner {
  background: #3d5ce41a !important;
  color: #3d5ce4 !important;
}

.listOverflowScroll {
  height: 200px;
  overflow: scroll;
}

.labelTypeBox {
  .el-radio-button {
    margin-right: 20px;
    margin-top: 20px;

    // 自定义单选框样式
    &::v-deep .el-radio-button__inner {
      border-radius: 4px;
      border-left: 1px solid #dcdfe6;
    }

    &::v-deep .el-radio-button__original-radio:checked+.el-radio-button__inner {
      background-color: white;
      color: #3d5ce4;
      border-color: #3d5ce4;
      border-left: 1px solid #3d5ce4;
      box-shadow: none;
    }
  }
}

.labelTypeBoxText,
.labelTypeBoxData {
  width: 70vw;

  .el-image {
    width: 100px;
    height: 80px;
  }

  .el-radio-button {
    margin-right: 20px;

    // 自定义单选框样式
    &::v-deep .el-radio-button__inner {
      border-radius: 4px;
      border-left: 1px solid #dcdfe6;
      font-size: 12px;
    }
  }
}

.colorBox {
  display: flex;
  flex-wrap: wrap;
  width: 50px;
}

.uploadBox {
  .uploadBoxBtn {
    text-align: center;

    .el-image {
      width: 56px;
      height: 56px;
      display: block;
      margin: 0 auto;
    }

    div {
      font-size: 12px;
      height: 20px;
    }
  }
}
</style>
